<template>
  <el-select
    v-model="selectedValues"
    filterable
    clearable
    :multiple="multiple"
    :placeholder="placeholder"
    :disabled="disabled"
    @change="handleChange"
  >
    <el-option-group
      v-for="group in filteredOptions"
      :key="group.label"
      :label="group.label"
    >
      <el-option
        v-for="item in group.childList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-option-group>
  </el-select>
</template>

<script setup lang="ts">
import {computed, nextTick, onMounted, ref, watch} from 'vue'
import {JustErpBasicShopApi} from '@/api/justerp/basic/shop'
import {isEqual} from "lodash-es";

// 定义选项类型
interface OptionItem {
  value: number | string
  label: string
}

interface OptionGroup {
  label: string
  childList: OptionItem[]
}

// 定义组件属性
const props = defineProps<{
  modelValue: number | string | (number | string)[] | null | undefined  // 标准的modelValue
  placeholder?: string
  disabled?: boolean
  multiple?: boolean
  shopIdFilter?: string | string[] | null | undefined  // 新增的过滤属性
}>()

// 定义组件事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: number | string | (number | string)[] | null | undefined): void
  (e: 'change', value: number | string | (number | string)[] | null): void
}>()

// 组件状态
const options = ref<OptionGroup[]>([])
const selectedValues = ref<number | string | (number | string)[] | null | undefined>(
  props.modelValue || (props.multiple ? [] : null)
)

// 处理shopIdFilter，统一转为Set便于查找
const allowedShopIds = computed<Set<string>>(() => {
  const filter = props.shopIdFilter;
  const ids = new Set<string>();

  if (!filter) return ids;

  // 处理逗号分隔的字符串
  if (typeof filter === 'string') {
    filter.split(',').forEach(id => {
      if (id.trim()) ids.add(id.trim());
    });
  }
  // 处理字符串数组
  else if (Array.isArray(filter)) {
    filter.forEach(id => {
      if (typeof id === 'string' && id.trim()) ids.add(id.trim());
    });
  }

  return ids;
});

// 计算过滤后的选项
const filteredOptions = computed<OptionGroup[]>(() => {
  const allowedIds = allowedShopIds.value;

  // 如果没有过滤条件，返回所有选项
  if (allowedIds.size === 0) return options.value;

  // 过滤选项组和子项
  return options.value.map(group => {
    const filteredChildren = group.childList.filter(item =>
      allowedIds.has(String(item.value))
    );
    return {
      ...group,
      childList: filteredChildren
    };
  }).filter(group => group.childList.length > 0); // 过滤掉没有子项的组
});

// 生命周期：挂载时获取数据
onMounted(() => {
  init()
})

// 监听父组件传值变化：只在值实际不同时更新 selectedValues
watch(
  () => props.modelValue,
  (newVal) => {
    nextTick(() => {
      // 处理空值（对齐 multiple 类型）
      const targetVal = newVal === undefined || newVal === null
        ? (props.multiple ? [] : null)
        : (Array.isArray(newVal) ? newVal.map(item => Number(item)) : Number(newVal));

      // 关键：值对比，不同才更新（避免无意义触发）
      if (!isEqual(selectedValues.value, targetVal)) {
        selectedValues.value = targetVal;
      }
    })
  },
  {immediate: true}
)

// 监听选中值变化：只在值实际不同时 emit
watch(
  selectedValues,
  (newVal, oldVal) => {
    // 关键：值对比，不同才 emit（打破循环）
    if (!isEqual(newVal, oldVal)) {
      emit('update:modelValue', newVal)
    }
  }
)

// 监听过滤条件变化，可能需要重新初始化
watch(
  () => props.shopIdFilter,
  () => {
    // 过滤条件变化时，如果已有数据则不需要重新请求，仅过滤即可
    // 如果需要重新请求数据，可以在这里调用 init()
  }
)

const init = async () => {
  try {
    const rawData = await JustErpBasicShopApi.treeShopData()

    // 确保正确映射label和value字段
    options.value = rawData.map(group => ({
      label: group.label || group.name,  // 增加容错
      childList: group.childList.map(item => ({
        value: item.value || item.shopId,  // 确保映射到正确的ID字段
        label: item.label || item.shopName  // 确保映射到正确的名称字段
      }))
    }))
  } catch (error) {
    console.error('获取店铺数据失败:', error)
    options.value = []
  }
}

// 处理变化事件
const handleChange = (newValue: number | string | (number | string)[] | null) => {
  emit('change', newValue)
}
</script>

<style scoped>
</style>
